package com.yikome.product.service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yikome.common.CommonService;
import com.yikome.product.entity.Category;
import com.yikome.product.repository.CategoryRepository;
import com.yikome.product.repository.ProductExtRepository;
import com.google.common.base.Preconditions;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Validator;

@Service
public class CategoryService extends CommonService<Category , Long>{

	@Autowired
    private CategoryRepository categoryRepository;

	@Autowired
	private ProductExtRepository productExtRepository ; 
	
    @Autowired
    public void setResourceDao(CategoryRepository repository) {
        super.setCommonDao(repository);
    }
    
    public List<Category> findCategory() {
        return categoryRepository.findAllCategory();
    }
    
    public List<Category> findCategoryFullTree() {
        List<Category> categoryRoots = new ArrayList<>();
        List<Category> categories = categoryRepository.findAllCategory();
        
        for (Iterator<Category> iterator = categories.iterator(); iterator.hasNext();) {
            Category category = iterator.next();
            if (category.getParentId() == 0) {
            	categoryRoots.add(category);
            	iterator.remove();
            }
        }
        for (Category root : categoryRoots) {
        	buildCategoryRoot(root, categories);
		}
        
        return categoryRoots;
    }
    
    private void buildCategoryRoot(Category root , List<Category> categories) {
    	for (Category category : categories) {
    		if (category.getParentId().longValue() == root.getId()) {
                if (root.getCategories() == null) {
                    root.setCategories(new ArrayList<>());
                } 
                root.getCategories().add(category);
            }
		}
    	if (root.getCategories() != null && !root.getCategories().isEmpty()) {
    		for (Category children : root.getCategories()) {
        		buildCategoryRoot(children, categories);
        	}
    	}
    }
    
    public List<Category> findCategoryTree(Long categoryId) {
        List<Category> fullTree = findCategoryFullTree();
        return categoryTreeHelp(fullTree, categoryId);
    }
    
    private List<Category> categoryTreeHelp(List<Category> categories, Long categoryId) {
        for (Category category : categories) {
            if (Validator.equal(category.getId(), categoryId)) {
                return category.getCategories();
            }
            if (category.getCategories() != null && !category.getCategories().isEmpty()) {
                return categoryTreeHelp(category.getCategories(), categoryId);
            }
        }
        return null;
    }
    
    @Transactional
    public Boolean deleteCategory(Long categoryId) {
    	Optional<Category> category = categoryRepository.findById(categoryId);
    	Preconditions.checkArgument(category.isPresent(), "分类信息不存在...");
    	List<Category> childrens = findCategoryTree(categoryId);
    	Preconditions.checkArgument(childrens == null || childrens.isEmpty(), "分类下有子类目,不允许删除...");
    	
    	categoryRepository.delete(category.get());
    	productExtRepository.changeProductCategory(null, categoryId);
    	
        return true;
    }
    
    public Category findCategory(Long categoryId) {
        Category category = find(categoryId);
        return category;
    }
    
    public Category findCategoryChildrens(Long categoryId) {
        Category category = find(categoryId);
        if (category == null || category.getYn() == 0) {
            return null;
        }
        category.setCategories(categoryRepository.findByParentId(category.getId()));
        return category;
    }
    
    /**
     *  如果是新增子分类,需要考虑原分类下是否有绑定商品,有的话,默认置空
     */
    @Transactional
    public Category saveCategory(Category category) {
    	
    	boolean needAsync = false;
    	if(category.getId() == null && category.getParentId() != null && category.getParentId() > 0) {//新增
    		needAsync = true ;
    	}
    	Category save = categoryRepository.save(category);
    	
    	if(needAsync) {
    		productExtRepository.changeProductCategory(save.getId(), category.getParentId());
    	}
    	
    	return save ; 
    }
}
